package 学生成绩查询管理系统.功能;

import 学生成绩查询管理系统.界面.Login;
import 学生成绩查询管理系统.界面.StudentSystem;
import 学生成绩查询管理系统.界面.TeacherFrame;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class TeacherScoreManager extends JFrame implements ActionListener {
    private JMenuItem reLogin;
    private JMenuItem menu;
    private JMenuItem exit;
    private JMenuItem aboutMe;
    String path = "C:\\Users\\23513\\Desktop\\学生成绩管理系统\\";
    private static final String URL = "jdbc:mysql://localhost:3306/studentmanager";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static Connection connection;
    private DefaultTableModel tableModel;
    private JTable dataTable;

    public TeacherScoreManager() {
        initializeDatabase();
        initializeMainFrame();
        queryRecords();
        initMenu();
    }

    private void initializeDatabase() {
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "无法连接到数据库", "错误", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }

    private void initializeMainFrame() {

        setTitle("成绩管理界面");
        setSize(600, 450);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        ImageIcon imageIcon = new ImageIcon("imge\\Login1.2.png");
        JLabel label = new JLabel(imageIcon);
        this.getContentPane().add(label, BorderLayout.CENTER);

        Toolkit tk = Toolkit.getDefaultToolkit();
        java.awt.Image img = tk.getImage( "imge\\成绩录入2.png");
        this.setIconImage(img);

        tableModel = new DefaultTableModel();
        tableModel.addColumn("ID");
        tableModel.addColumn("姓名");
        tableModel.addColumn("课程");
        tableModel.addColumn("成绩");

        dataTable = new JTable(tableModel);

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加数据");
        JButton displayButton = new JButton("显示数据");
        JButton deleteButton = new JButton("删除数据");
        JButton queryByIdButton = new JButton("查询ID");

        buttonPanel.add(addButton);
        buttonPanel.add(displayButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(queryByIdButton);

        addButton.addActionListener(e -> showAddDataDialog());
        displayButton.addActionListener(e -> showDisplayDataDialog());
        deleteButton.addActionListener(e -> deleteSelectedRecord());
        queryByIdButton.addActionListener(e -> showQueryByIdDialog());

        add(buttonPanel, BorderLayout.NORTH);
        // 使用JScrollPane包裹JTable，添加滚动条
        add(new JScrollPane(dataTable), BorderLayout.CENTER);
    }
    private void initMenu() {
        JMenuBar jMenuBar = new JMenuBar();
        JMenu about = new JMenu("关于我");
        JMenu function = new JMenu("功能");
        aboutMe = new JMenuItem("QQ二维码");
        reLogin = new JMenuItem("重新登录");
        menu = new JMenuItem("主页");
        exit = new JMenuItem("退出");

        about.add(aboutMe);
        function.add(reLogin);
        function.add(menu);
        function.add(exit);

        aboutMe.addActionListener(this);
        reLogin.addActionListener(this);
        menu.addActionListener(this);
        exit.addActionListener(this);

        jMenuBar.add(about);
        jMenuBar.add(function);
        this.setJMenuBar(jMenuBar);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // 获取当前被点击的条目对象
        Object obj = e.getSource();
        if (obj == reLogin) {
            dispose();
            new Login();
        } else if (obj == menu) {
            dispose();
            new TeacherFrame();
        } else if (obj == exit) {
            System.exit(0);
        } else if (obj == aboutMe) {
            // 创建一个弹框对象
            JDialog jDialog = new JDialog();
            Toolkit tk = Toolkit.getDefaultToolkit();
            Image img = tk.getImage("imge\\成绩录入2.png");
            jDialog.setIconImage(img);
            // 创建一个管理图片的容器对象JLabel
            JLabel jLabel = new JLabel(new ImageIcon("imge\\about.png"));
            // 设置位置和宽高
            jLabel.setBounds(0, 0, 300, 380);
            // 把图片添加到弹框当中
            jDialog.getContentPane().add(jLabel);
            // 给弹框设置大小
            jDialog.setSize(400, 400);
            // 让弹框置顶
            jDialog.setAlwaysOnTop(true);
            // 让弹框居中
            jDialog.setLocationRelativeTo(null);
            // 弹框不关闭则无法操作下面的界面
            jDialog.setModal(true);
            // 让弹框显示出来
            jDialog.setVisible(true);
        }

    }

    private void showAddDataDialog() {
        AddDataDialog addDataDialog = new AddDataDialog(this, "添加数据", true);
        addDataDialog.setLocationRelativeTo(this);
        addDataDialog.setVisible(true);
    }

    private void showDisplayDataDialog() {
        queryRecords();
    }

    private void queryRecords() {
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT * FROM score");

            // Clear the table model
            tableModel.setRowCount(0);

            // Populate the table model with data from the database
            while (resultSet.next()) {
                Object[] rowData = {
                        resultSet.getInt("ID"),
                        resultSet.getString("name"),
                        resultSet.getString("course"),
                        resultSet.getDouble("score")
                };
                tableModel.addRow(rowData);
            }

            // Close resources
            resultSet.close();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "查询数据失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteSelectedRecord() {
        int selectedRow = dataTable.getSelectedRow();

        if (selectedRow != -1) {
            int idToDelete = (int) dataTable.getValueAt(selectedRow, 0);

            try {
                String deleteQuery = "DELETE FROM score WHERE ID=?";
                try (PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery)) {
                    preparedStatement.setInt(1, idToDelete);
                    preparedStatement.executeUpdate();
                }

                // Update the table model after deletion
                queryRecords();

                JOptionPane.showMessageDialog(this, "记录删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (SQLException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "删除记录失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的记录", "警告", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void showQueryByIdDialog() {
        String idString = JOptionPane.showInputDialog(this, "请输入要查询的ID:");
        if (idString != null && !idString.trim().isEmpty()) {
            try {
                int id = Integer.parseInt(idString);
                queryRecordById(id);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的ID", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void queryRecordById(int id) {
        try {
            String queryById = "SELECT * FROM score WHERE ID=?";
            try (PreparedStatement preparedStatement = connection.prepareStatement(queryById)) {
                preparedStatement.setInt(1, id);
                ResultSet resultSet = preparedStatement.executeQuery();

                // Clear the table model
                tableModel.setRowCount(0);

                // Populate the table model with data from the database
                while (resultSet.next()) {
                    Object[] rowData = {
                            resultSet.getInt("ID"),
                            resultSet.getString("name"),
                            resultSet.getString("course"),
                            resultSet.getDouble("score")
                    };
                    tableModel.addRow(rowData);
                }

                // Close resources
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "查询数据失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private static class AddDataDialog extends JDialog {
        private JTextField idTextField;
        private JTextField nameTextField;
        private JTextField courseTextField;
        private JTextField scoreTextField;

        public AddDataDialog(JFrame parent, String title, boolean modal) {
            super(parent, title, modal);
            setSize(300, 200);

            idTextField = new JTextField(15);
            nameTextField = new JTextField(15);
            courseTextField = new JTextField(15);
            scoreTextField = new JTextField(15);

            JButton addButton = new JButton("添加");
            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    addRecord();
                }
            });

            JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
            panel.add(new JLabel("ID:"));
            panel.add(idTextField);
            panel.add(new JLabel("姓名:"));
            panel.add(nameTextField);
            panel.add(new JLabel("课程:"));
            panel.add(courseTextField);
            panel.add(new JLabel("成绩:"));
            panel.add(scoreTextField);
            panel.add(new JLabel());
            panel.add(addButton);

            add(panel);
        }

        private void addRecord() {
            try {
                int id = Integer.parseInt(idTextField.getText());
                String name = nameTextField.getText();
                String course = courseTextField.getText();
                double score = Double.parseDouble(scoreTextField.getText());

                String insertQuery = "INSERT INTO score (ID, name, course, score) VALUES (?, ?, ?, ?)";
                try (PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
                    preparedStatement.setInt(1, id);
                    preparedStatement.setString(2, name);
                    preparedStatement.setString(3, course);
                    preparedStatement.setDouble(4, score);

                    preparedStatement.executeUpdate();
                }

                ((TeacherScoreManager) getParent()).queryRecords();

                JOptionPane.showMessageDialog(this, "记录添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (NumberFormatException | SQLException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "添加记录失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            TeacherScoreManager teacherScoreManager = new TeacherScoreManager();
            teacherScoreManager.setVisible(true);
        });
    }
}

